//
//  ZSStatusViewModel.swift
//  ZSWeibo
//
//  Created by zsj1992 on 16/4/13.
//  Copyright © 2016年 ichange. All rights reserved.
//

import UIKit

class ZSStatusViewModel: NSObject {
    
    //正则表达式对象
    static let topicRegex = try!NSRegularExpression(pattern: "#.*?#", options: [])
    
    let WeiboContentLabelFont: CGFloat = 15
    
    var status:ZSStatus?
    
    var imgIcon:NSURL?
    
    var mbImage:UIImage?
    
    var verifiedImage:UIImage?
    
    var repostTitle:String?
    
    var commentTitle:String?
    
    var likeTitle:String?
    
    var creatTime:String?{//这里搞成了一个计算型属性
    
        let date = NSDate.sinaDate((status?.created_at)!)
        
         let creatTime = date?.fullDescription()

        return creatTime
    }
    
    
    var source : String?
    
    
    //属性文本
    var originalAttributeString : NSAttributedString?
    
    var retwetedAttributeString : NSAttributedString?

    
    
    
    
    
    //配图相关:viewModel提供一个图片数组
    var pictures:[UIImage]?

    
    
    
    
    //初始化的时候带一个status模型,初始化的时候,处理好数据
    init( status:ZSStatus) {
        
        super.init()
        
        self.status = status
        
        self.imgIcon = NSURL(string: (status.user?.profile_image_url)!)
        
        dealMbImg()
        
        dealVerifiedImage()
        
        dealBtnTitle()
        
        dealWithSource()
        
       originalAttributeString = dealWeiboText(source: status.text ?? "")
        
        retwetedAttributeString = dealWeiboText(source: status.retweeted_status?.text ?? "")

        
    }
}


//希望是处理之后,视图拿到viewModel,就可以直接进行设置

extension ZSStatusViewModel{
    
    //处理等级图片
    func dealMbImg(){
        
        let imgName = "common_icon_membership_level\((status?.user?.mbrank)!)"
        
        mbImage = UIImage(named: imgName)
        
        
    }
    
    //处理认证图片
    func dealVerifiedImage(){
        
        let x = status?.user?.verified_type
        
        var name:String = ""
        
        if x == -1{
            name = ""
        }
        else if (x == 2 || x==3 || x==5){
            name = "avatar_enterprise_vip"
        }
        else if (x==1){
            name = "avatar_vip"
        }
        else{
            name = "avatar_grassroot"
        }
        
        verifiedImage = UIImage(named: name)
    }
    
    //处理按钮的文字
    func dealBtnTitle(){
        
        //评论
        if status?.comments_count != 0{
            
            if status?.comments_count > 10000{
                
                
                commentTitle = "\(CGFloat((status?.comments_count)!/1000)/10)万"
                
            }else{
                
                commentTitle = "\((status?.comments_count)!)"
            }
        }
        else{
            self.commentTitle = "评论"
        }
        
        
        //转发
        if status?.reposts_count != 0{
            
            if status?.reposts_count > 10000{
                
                repostTitle = "\(CGFloat((status?.reposts_count)!/1000)/10)万"
            }else{
                
                repostTitle = "\((status?.reposts_count)!)"
            }
        }
        else{
            self.repostTitle = "转发"
        }
        
        
        //赞
        if status?.attitudes_count != 0{
            
            if status?.attitudes_count > 10000{
                
                likeTitle = "\(CGFloat((status?.attitudes_count)!/1000)/10)万"
            }else{
                
                likeTitle = "\((status?.attitudes_count)!)"
            }
        }
        else{
            self.likeTitle = "赞"
        }
    }

    //处理微博来源
    func dealWithSource(){

        
        let startFlag = "\">"
        let endFlag = "</"
        
        let str = status?.source ?? ""
        
        if let startRange = str.rangeOfString(startFlag), endRange = str.rangeOfString(endFlag) {
            
        let range = startRange.endIndex..<endRange.startIndex
            
        source = str.substringWithRange(range)
        
//            print(source)
            
        }
    }
    
}


extension ZSStatusViewModel{
    /**
     
     怎么处理一下,是的
     怎么显示表情图片???
     
     点击了表情键盘的时候,通过通知的方式通知到发布控制器,把表情插入textView中间(通知传了一个参数em:HMEmoticon) --> 判断em是什么表情(空表情??emoji表情??删除)->还有就是图片表情按钮
     
     -->如果是想要插入表情图片,需要利用附件类型--->把表情转为属性文本
     

     */
    
    
    
    
    
    
    
    
    
    func dealWeiboText(source text:String)->NSAttributedString{

        //在微博正文中查找表情文字
        let pattern = "\\[(.*?)\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //通过正则表达式匹配对应的字符串
    
//        let str = status?.text ?? ""
        
        let results = regex.matchesInString(text, options: [], range: NSRange(location: 0, length: text.characters.count))
        
        let strM = NSMutableAttributedString(string: text)

        //倒着遍历结果数组
        for res in results.reverse(){
            
        let range = res.rangeAtIndex(0)
            
        let subStr = (text as NSString).substringWithRange(range)

        if let em = findEmoticonWithEmoticonText(subStr){
                let imageText = HMEmoticonAttachment.emoticonImageToAttributeString(em, font: UIFont.systemFontOfSize(WeiboContentLabelFont))
                
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
        }
        
        topicAddHighlighted(strM)
        
        return strM
    }

    
    func topicAddHighlighted(strM:NSMutableAttributedString){
    
        //1.查找话题字符串
        let sourceText = strM.string

        //匹配话题字符串
        let results = ZSStatusViewModel.topicRegex.matchesInString(sourceText, options: [], range: NSRange(location: 0, length: sourceText.characters.count))
        
        //遍历结果
        for res in results{
        
            let range = res.rangeAtIndex(0)
            let subStr = (sourceText as NSString).substringWithRange(range)
       
        strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range)
        
        }
        
    
    }
    
    
    
    //根据表情字符串
    func findEmoticonWithEmoticonText(subStr:String)->HMEmoticon?{
    
        for p in HMEmoticonManager.sharedEmoticon.packages{
        
            for emoticons in p.sectionEmoticon{
            
            let array = emoticons.filter({ (em) -> Bool in
                return em.chs == subStr
            })
                if array.count != 0{
                return array.first
                }
            }
        }
        return nil
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
}








